package com.lfd.rabbitmq.service;

import com.lfd.rabbitmq.config.NewRabbitConfig;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

/**
 * @项目名： spring-emq
 * @包名： com.lfd.rabbitmq.service
 * @文件名: NewMessageConsumer
 * @创建者: liufudong@szyh-smart.com
 * @创建时间: 2024/10/11 19:56
 * @描述：3. 消费者配置和实现
 */
@Slf4j
@Service
public class NewMessageConsumer {
    @RabbitListener(queues = NewRabbitConfig.QUEUE_NAME_A)
    public void receive(Message message, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            String receivedMessage  = new String(message.getBody(), "UTF-8");
            // 处理消息
            log.info("NewMessageConsumer Received message: {}", receivedMessage);
            // 发送ACK确认
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.info("NewMessageConsumer Message handling failed: {}", new String(message.getBody()));
            try {
                // 处理失败时拒绝消息，重新入队
                channel.basicNack(deliveryTag, false, true);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
